<template>
  <el-container>
    <el-header>
      <el-button type="primary" @click="handleAddStaff">添加员工<i class="el-icon-circle-plus-outline"></i></el-button>
      <staff-insert-view
          ref="staffInsertView"
          :message="showInsert"
          :dialog-title="dialogTitle"
          @close="listClose">
      </staff-insert-view>
    </el-header>
    <el-container>
      <el-header>
        <el-form :inline="true" :model="adminRole" class="demo-form-inline">
          <el-form-item label="职业">
            <el-select v-model="adminRole.roleId" placeholder="请选择你要查询的职业" clearable>
              <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="电话号码">
            <el-input v-model="adminRole.admin.phone" placeholder="请输入你要查询的电话号码" clearable></el-input>
          </el-form-item>
          <el-button type="primary" @click="getAllAdminRole(1)">查询</el-button>
        </el-form>
      </el-header>
      <el-main>
        <el-table
            :data="pageInfo.list"
            border
            style="width: 100%"
            v-loading="loading">
          <el-table-column
              prop="admin.adminName"
              label="用户名/姓名"
              width="150">
          </el-table-column>
          <el-table-column
              prop="admin.adminPass"
              label="密码"
              width="120">
          </el-table-column>
          <el-table-column
              prop="admin.phone"
              label="电话"
              width="120">
          </el-table-column>
          <el-table-column
              prop="admin.email"
              label="邮箱"
              width="180">
          </el-table-column>
          <el-table-column
              prop="role.name"
              label="职位"
              width="120">
          </el-table-column>
          <el-table-column
              prop="admin.gender"
              label="性别"
              width="50">
          </el-table-column>
          <el-table-column
              prop="admin.creatTime"
              label="入职时间"
              width="150">
          </el-table-column>
          <el-table-column
              prop="admin.inNum"
              label="身份证号"
              width="190">
          </el-table-column>
          <el-table-column
              prop="admin.photoRight"
              label="身份证照片正面"
              width="180">
            <template slot-scope="scope">
              <!-- 通过 this.$basePath 访问 -->
              <img
                  :src="`${$basePath}static/uploadImages/${scope.row.admin.photoRight}`"
                  alt="身份证照片"
                  v-if="scope.row.admin.photoRight"
                  width="150"
                  height="150"
              >
              <span v-else>无照片</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="admin.photoBack"
              label="身份证照片反面"
              width="180">
            <template slot-scope="scope">
              <!-- 通过 this.$basePath 访问 -->
              <img
                  :src="`${$basePath}static/uploadImages/${scope.row.admin.photoBack}`"
                  alt="身份证照片"
                  v-if="scope.row.admin.photoBack"
                  width="150"
                  height="150"
              >
              <span v-else>无照片</span>
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="250">
            <template slot-scope="scope">
              <div v-if="scope.row.admin.adminName != 'admin'">
                <el-button
                    type="text"
                    size="small"
                    @click="handleUpdate(scope.row)">
                  修改
                </el-button>
                <el-button
                    type="text"
                    size="small"
                    @click="handleExple(scope.row)">
                  开除
                </el-button>
                <el-button
                    type="text"
                    size="small"
                    @click="handleExcel(scope.row)">
                  生成该员工的操作日志
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            @current-change="handlePageNumChange"
            :current-page="pageInfo.pageNum"
            :page-size="pageInfo.pageSize"
            :total="pageInfo.total">
        </el-pagination>
      </el-main>
    </el-container>
  </el-container>
</template>
<script>
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import StaffInsertView from "@/views/admin/StaffInsertView.vue";
export default {
  name: "StaffListView",
  components: {
    // 步骤2：局部注册组件（注意驼峰命名）
    StaffInsertView
  },
  data() {
    return {
      loading: false,
      adminRole:{
        roleId:null,
        admin:{
          phone:null,
        }
      },
      staff:{},
      showInsert:false,
      dialogTitle: '添加员工',
      roleList:[],
      pageInfo:[],
      tableData: []
    }
  },
  created() {
    this.getAllAdminRole(1);
    this.getAdminRole();
  },
  methods: {
    listClose(val){
      this.showInsert = val;
      this.getAllAdminRole(1);
    },
    getAdminRole() {
      this.axios.get("/admin/adminRole").then(res => {
        this.roleList = res.data.roleList;
      });
    },
    getAllAdminRole(pageNum) {
      this.loading = true;
      this.axios.post("/adminRole/list",this.adminRole,{params:{pageNum:pageNum}}).then(res => {
        this.pageInfo = res.data.adminRolePageInfo;
        this.loading = false;
      });
    },
    handleAddStaff() {
      this.showInsert = true;
      this.dialogTitle = '添加员工';
    },
    handleUpdate(row) {
      this.staff = row;
      this.$refs.staffInsertView.update(row);
      this.showInsert = true;
      this.dialogTitle = '修改员工';
    },
    handleExple(row) {
      const id = parseInt(row.adminId);
      if (isNaN(id)) {
        this.$message.error("ID无效");
        return;
      }
      this.$confirm('你真的要开除【'+row.role.name+'】:【'+row.admin.adminName+'】？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.delete("/admin/delete",{
          params:{id:id}
        })
            .then(res => {
              this.getAllAdminRole(1);
              this.$message.success('删除成功');
            }).catch(err => {
          this.$message.error('删除失败: ' + err.message);
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleExcel(row) {
      this.axios.get('/admin/operationLog/'+row.adminId).then(res => {
            this.tableData = res.data.operationLogs;
            const customHeaders = ['物业操作人员', '住户操作人员', '登录IP地址', '操作'];
            const customData = this.tableData.map(item => ({
              '物业操作人员': item.admin?.adminName ?? '无',
              '住户操作人员': item.user?.userName ?? '无',
              '登录IP地址': item.ip ?? '无',
              '操作': item.info ?? '无'
            }));
// 2. 生成工作表
        if (!customData || customData.length === 0) {
          this.$message.warning('该员工暂时还没有进行任何操作');
          return;
        }
        const worksheet = XLSX.utils.json_to_sheet(customData);

// 3. 覆盖表头（确保名称和顺序一致）
        XLSX.utils.sheet_add_aoa(worksheet, [customHeaders], { origin: 'A1' });

// 4. 删除多余列（如果有）
        const maxCol = XLSX.utils.decode_range(worksheet['!ref']).e.c;
        if (maxCol > customHeaders.length - 1) {
          for (let C = customHeaders.length; C <= maxCol; C++) {
            XLSX.utils.sheet_delete_cols(worksheet, C);
          }
        }

// 6. 保存文件（后续代码不变）
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '用户信息');
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
        saveAs(blob, row.role.name+':'+row.admin.adminName+'的操作日志.xlsx');
      });
    },
    handlePageNumChange(pageNum) {
      this.getAllAdminRole(pageNum);
    }
  }
}
</script>
<style>

</style>